package com.tianlan.blog.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.tianlan.blog.dao.SysRoleResourceDao;
import com.tianlan.blog.dto.UpdateRoleResource;
import com.tianlan.blog.entity.SysRoleResource;
import com.tianlan.blog.service.SysRoleResourceService;

@Service
public class SysRoleResourceServiceImpl implements SysRoleResourceService {
	
	@Autowired
	private SysRoleResourceDao sysRoleResourceDao;

	@Override
	public List<SysRoleResource> selectSysRoleResourceByRoleId(Integer roleId) {
		return sysRoleResourceDao.findAllByRoleIdAndDelFlag(roleId,"0");
	}

	@Override
	@CacheEvict(value = "resources", allEntries = true)
	public boolean updateList(UpdateRoleResource updateRoleResource) {
		List<SysRoleResource> addRoleResourceList = updateRoleResource.getAddResources();
        if (!CollectionUtils.isEmpty(addRoleResourceList)) {
        	 addRoleResourceList = sysRoleResourceDao.saveAll(addRoleResourceList);
        }
        
        int deleteRoleResource = 0;
        List<SysRoleResource> deleteRoleResourceList = updateRoleResource.getDelResources();
        if (!CollectionUtils.isEmpty(deleteRoleResourceList)) {
        	Integer roleId = updateRoleResource.getRoleId();
            List<Integer> resourceIdS = new ArrayList<>();
            for (SysRoleResource roleResource : deleteRoleResourceList) {
            	resourceIdS.add(roleResource.getResourceId());
            }
            deleteRoleResource = sysRoleResourceDao.deleteRoleResourceByRoleIdAndResourceIdS(roleId, resourceIdS);
        }
		return !CollectionUtils.isEmpty(addRoleResourceList) || deleteRoleResource != 0;
	}

}
